﻿using System;
using System.Collections.Generic;
using System.IO;
using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using DHJ.Cost.Authorization;
using Newtonsoft.Json.Linq;

namespace DHJ.Cost
{
    /// <summary>
    /// Application layer module of the application.
    /// </summary>
    [DependsOn(
        typeof(CostCoreModule)
        )]
    public class CostApplicationModule : AbpModule
    {
        public override void PreInitialize()
        {
            //Adding authorization providers
            Configuration.Authorization.Providers.Add<AppAuthorizationProvider>();

            //Adding custom AutoMapper configuration
            Configuration.Modules.AbpAutoMapper().Configurators.Add(CustomDtoMapper.CreateMappings);

            // Adding Cost Categories
            IocManager.Register<CostCategoryConfig>();
            Configuration.Modules.CostCategory().Categories = GetCategoriesByJson();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(CostApplicationModule).GetAssembly());
        }


        private ICollection<CostConfigCategory> GetCategoriesByJson()
        {
            var costSettingsJson = JObject.Parse(File.ReadAllText("costsettings.json"));

            var jsonCategories = (JArray)costSettingsJson["Categories"];

            var categories = new List<CostConfigCategory>();

            foreach (JToken jsonCategory in jsonCategories)
            {
                var category = new CostConfigCategory(jsonCategory["Key"]?.ToString(), jsonCategory["Value"]?.ToString(), new List<CostConfigType>());

                var jsonTypes = (JArray)jsonCategory["Types"];

                foreach (JToken jsonType in jsonTypes)
                {
                    var type = new CostConfigType(jsonType["Key"]?.ToString(), jsonType["Value"]?.ToString());

                    category.Types.Add(type);
                }

                categories.Add(category);
            }

            return categories;
        }
    }
}